package com.ls.pattern.establish.single;

//1)饿汉式(静态常量)
public class SingletonExample {

    public static void main(String[] args) {

    }
}

//1)饿汉式(静态常量)
class Singleton1 {
    private final static Singleton1 instance = new Singleton1();

    private Singleton1() {
    }

    public static Singleton1 getInstance() {
        return instance;
    }
}

//2)饿汉式(静态代码块)
class Singleton2 {
    private static Singleton2 instance;

    static {
        instance = new Singleton2();
    }

    private Singleton2() {
    }


    public static Singleton2 getInstance() {
        return instance;
    }
}
//3)懒汉式(线程不安全)
class Singleton3 {
    private static Singleton3 instance;
    private Singleton3() {
    }
    public static Singleton3 getInstance() {
        if (instance == null){
            instance = new Singleton3();
        }
        return instance;
    }
}

//4)懒汉式(线程安全,同步方法)
class Singleton4 {
    private static Singleton4 instance;
    private Singleton4() {
    }
    public static synchronized Singleton4 getInstance() {
            if (instance == null){
                instance = new Singleton4();
            }
        return instance;
    }
}
//5)懒汉式(线程安全,同步代码块)
class Singleton5 {
    private static Singleton5 instance;
    private Singleton5() {
    }
    public static Singleton5 getInstance() {
        if (instance == null){
            synchronized (Singleton5.class){
                instance = new Singleton5();
            }
        }
        return instance;
    }
}
//6)双重检查
class Singleton6 {
    private static volatile Singleton6 instance;
    private Singleton6() {
    }
    public static Singleton6 getInstance() {
        if (instance == null){
            synchronized (Singleton6.class){
                if (instance == null){
                    instance = new Singleton6();
                }
            }
        }
        return instance;
    }
}
//7)静态内部类   推荐使用
class Singleton7 {

    private Singleton7() {
    }

    private static class SingletonInstance{
        //只会在调用getInstance方法是才会加载这个类
        private static final Singleton7 INSTANCE = new Singleton7();
    }
    public static Singleton7 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}
//8)枚举  推荐使用
enum Singleton8{
    INSTANCE;
    public void sayHello(){
        System.out.println("hello");
    }
}


















